<?php
/**
 * 密码加密函数
 */
function encode_password($password){
    return sha1(md5($password));
}

/*
* 生成唯一激活码
*/
function build_activationkey(){
    $str = substr(uniqid(), 7, 13);//获取一个基于当前的微秒数生成的唯一不重复的字符串，去掉前8位变化缓慢的字符
    $str.= 'jxzhjy';//固定添加
    $str.= rand(0, 9);//随机添加
    return substr(md5($str), 8, 16);
}

/*
* 将token中的user_id解析出来
*/
function tokenToUid($token = ''){
    if(!$token){
        return 0;
    }
    $token = str_replace(' ', '+', $token);
    
    $auth = daddslashes(explode("\t", authcode($token, 'DECODE')));
    $uid = isset($auth[1]) ? $auth[1] : 0;
    
    return $uid;
}

// 判断点 是否在多边形 内 
//isPointInPolygon($tmpArr[0], ['lng' => 120.756802, 'lat' => 30.776139]);
function isPointInPolygon($polygon, $lnglat){
    $count = count($polygon);
    $px = $lnglat['lat'];
    $py = $lnglat['lng'];
    $flag = false;
    for($i = 0, $j = $count - 1; $i < $count; $j = $i, $i++){
        $sy = $polygon[$i]['lng'];
        $sx = $polygon[$i]['lat'];
        $ty = $polygon[$j]['lng'];
        $tx = $polygon[$j]['lat'];
        if($px == $sx && $py == $sy || $px == $tx && $py == $ty){
            return true;
        }
        if($sy < $py && $ty >= $py || $sy >= $py && $ty < $py){
            $x = $sx + ($py - $sy) * ($tx - $sx) / ($ty - $sy);
            if($x == $px){
                return true;
            }
            if($x > $px){
                $flag = !$flag;
            }
        }
    }
    
    return $flag;
}

function encrypt($data, $key = 'qytch')
{
    $key = md5($key);
    $x  = 0;
    $len = strlen($data);
    $l  = strlen($key);
	$char = $str = '';
    for ($i = 0; $i < $len; $i++)
    {
        if ($x == $l) 
        {
         $x = 0;
        }
        $char .= $key{$x};
        $x++;
    }
    for ($i = 0; $i < $len; $i++)
    {
        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
    }
    return base64_encode($str);
}

function decrypt($data, $key = 'qytch')
{
    $key = md5($key);
    $x = 0;
    $data = base64_decode($data);
    $len = strlen($data);
    $l = strlen($key);
	$char = $str = '';
    for ($i = 0; $i < $len; $i++)
    {
        if ($x == $l) 
        {
         $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++)
    {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
        {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }
        else
        {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return $str;
}

if ( ! function_exists('is_php'))
{
	/**
	 * Determines if the current version of PHP is equal to or greater than the supplied value
	 *
	 * @param	string
	 * @return	bool	TRUE if the current version is $version or higher
	 */
	function is_php($version)
	{
		static $_is_php;
		$version = (string) $version;

		if ( ! isset($_is_php[$version]))
		{
			$_is_php[$version] = version_compare(PHP_VERSION, $version, '>=');
		}

		return $_is_php[$version];
	}
}

// 获取传统url上面的参数
function getUrlData($key = '', $default = 0){
    //先对url进行获取
    $url = $_SERVER['REQUEST_URI'];
    //取出问号以前的内容
    $tmpArr = explode('?', $url);
    $str = $tmpArr[1];

    //拆分一共有多少个数组
    $paramArr = explode('&', $str);

    $uriData = [];

    if(!empty($paramArr) && is_array($paramArr)){
        foreach ($paramArr as $item) {
            //拆分一下item
            $tmp = explode('=', $item);
            $uriData[$tmp[0]] = $tmp[1];
        }
    }

    if($key){//如果传递进来了这个
        return isset($uriData[$key]) ? $uriData[$key] : $default;
    }
    else{
        return $uriData;
    }
}

function P($obj){
    echo '<pre>';
    var_dump($obj);
    echo '</pre>';
}

function random($length = 6, $numeric = 0){
    PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    if($numeric) {
        $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
    }
    else{
        $hash = '';
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
    }
    return $hash;
}

function xml_to_array($xml){
    $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
    if(preg_match_all($reg, $xml, $matches)){
        $count = count($matches[0]);
        for($i = 0; $i < $count; $i++){
        $subxml= $matches[2][$i];
        $key = $matches[1][$i];
            if(preg_match( $reg, $subxml )){
                $arr[$key] = xml_to_array( $subxml );
            }
            else{
                $arr[$key] = $subxml;
            }
        }
    }
    return $arr;
}

function Post($curlPost, $url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    $return_str = curl_exec($curl);
    curl_close($curl);
    return $return_str;
}

if ( ! function_exists('is_cli'))
{
    /**
     * Is CLI?
     *
     * Test to see if a request was made from the command line.
     *
     * @return 	bool
     */
    function is_cli()
    {
        return (PHP_SAPI === 'cli' OR defined('STDIN'));
    }
}

if ( ! function_exists('mkdirs'))
{
    function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
        if (!mkdirs(dirname($dir), $mode)) return FALSE;
        return @mkdir($dir, $mode);
    }
}

//系统后台权限校验
function check_auth($auth){
    $aAuth = Yaf_Session::getInstance()->__get('a_auth');
    $aType = Yaf_Session::getInstance()->__get('a_type');
    
    if($aType == 1 || $aType == -99){//管理员和超级管理员直接放行
        return true;
    }
    
    if(!empty($aAuth) && is_array($aAuth)){
        if(in_array($auth, $aAuth)){
            return true;
        }
    }
    
    return false;
}

function cmd5($pwd, $salt = 'ycweb'){
    return md5(md5($pwd.$salt));
}

// Anti_SQL Injection, escape quotes
function filter($content) {
    if (!get_magic_quotes_gpc()) {
        return addslashes($content);
    } else {
        return $content;
    }
}

//对字符串等进行过滤
function filterStr($arr) {  
    if (!isset($arr)) {
        return null;
    }

    if (is_array($arr)) {
        foreach ($arr as $k => $v) {
            if(is_array($v)){
                $arr[$k] = filterStr($v);
            }
            else{
                $arr[$k] = filter(stripSQLChars(stripHTML(trim($v), true)));
            }
        }
    } else {
        $arr = filter(stripSQLChars(stripHTML(trim($arr), true)));
    }

    return $arr;
}

function stripHTML($content, $xss = true) {
    $search = array("@<script(.*?)</script>@is",
        "@<iframe(.*?)</iframe>@is",
        "@<style(.*?)</style>@is",
        "@<(.*?)>@is"
    );

    $content = preg_replace($search, '', $content);

    if($xss){
        $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 
        'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 
        'layer', 'bgsound', 'title', 'base');
                                
        $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy',      'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
        $ra = array_merge($ra1, $ra2);
        
        $content = str_ireplace($ra, '', $content);
    }

    return strip_tags($content);
}

function removeXSS($val) {
    // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
    // this prevents some character re-spacing such as <javaΘscript>
    // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
    $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);

    // straight replacements, the user should never need these since they're normal characters
    // this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        // ;? matches the ;, which is optional
        // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

        // &#x0040 @ search for the hex values
        $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
        // @ @ 0{0,7} matches '0' zero to seven times
        $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
    }

    // now the only remaining whitespace attacks are \t, \n, and \r
    $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 
                            'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 
                            'layer', 'bgsound', 'title', 'base');
                            
    $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy',      'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra = array_merge($ra1, $ra2);

    $found = true; // keep replacing as long as the previous round replaced something
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
                    $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
                    $pattern .= ')?';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
            $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
            if ($val_before == $val) {
                // no replacements were made, so exit the loop
                $found = false;
            }
        }
    }

    return $val;
}

/**
 *  Strip specail SQL chars
 */
function stripSQLChars($str) {
    $replace = array('SELECT', 'INSERT', 'DELETE', 'UPDATE', 'CREATE', 'DROP', 'VERSION', 'DATABASES',
        'TRUNCATE', 'HEX', 'UNHEX', 'CAST', 'DECLARE', 'EXEC', 'SHOW', 'CONCAT', 'TABLES', 'CHAR', 'FILE',
        'SCHEMA', 'DESCRIBE', 'UNION', 'JOIN', 'ALTER', 'RENAME', 'LOAD', 'FROM', 'SOURCE', 'INTO', 'LIKE', 'PING', 'PASSWD');
    
    return str_ireplace($replace, '', $str);
}

// Redirect directly
function redirect($URL = '', $second = 0) {
    if (!isset($URL)) {
        $URL = $_SERVER['HTTP_REFERER'];
    }

    ob_start();
    ob_end_clean();
    header("Location: ".$URL, TRUE, 302); //header("refresh:$second; url=$URL", TRUE, 302);
    ob_flush(); //可省略
    exit;
}


// Redirect and display message
function gotoURL($message = '', $URL = '') {
    if (!isset($URL)) {
        $URL = $_SERVER['HTTP_REFERER'];
    }

    if (isset($message)) {
        jsAlert($message);
    }

    echo "<script type='text/javascript'>window.location.href='$URL'</script>";
}

/*
 *Functionality: Generate Single-language[Chinese-simplified] pagenation navigator
  @Params:
  Int $page: current page
  Int $totalPages: total pages
  String $URL: target URL for pagenation
  Int $count: total records
  String $query: query string for SEARCH
 *  @Return: String pagenation navigator link
 */
function generatePageLink($page, $totalPages, $URL, $counts, $query = '') {
	$page = $page ? $page : 1;

    $URL .= (strpos($URL, '?') === FALSE ? '?' : '&');

    $link = '<ul class="pagination pull-right no-margin">';
    if($page == 1){
        $link .= '<li class="prev disabled">
                    <a href="#">
                        <i class="ace-icon fa fa-angle-double-left"></i>
                    </a>
                </li>';
    }else{
        $prev  = $URL.'page='.($page - 1).$query;
        $link .= '<li class="prev">
                    <a href="'.$prev.'">
                        <i class="ace-icon fa fa-angle-double-left"></i>
                    </a>
                </li>';
    }

    // 超过 10 页则要考虑前二后二中四
    if($totalPages > 10){
        $sep = TRUE;
    }

    $first = $URL.'page=1'.$query;
    if($page == 1){
        $active = 'active';
    }else{
        $active = '';
    }

    $link .= '<li class="'.$active.'">
                <a href="'.$first.'">1</a>
            </li>';

    if($totalPages >= 2){
        $second = $URL.'page=2'.$query;
        if($page == 2){
            $active = 'active';
        }else{
            $active = '';
        }

        $link .= '<li class="'.$active.'">
                    <a href="'.$second.'">2</a>
                </li>';
    }

    if($sep){
        if(($page - 2) > 3){
            $link .= '<li>
                   <a href="#">...</a>
                </li>';
        } 

        // 取中间四个
        for($i = ($page - 2); $i <= ($page + 2); $i++){
            if($i <= 2 || $i > ($totalPages - 2)){
                continue;
            }

            if($i > $totalPages){
                break;
            }

            if($page == ($totalPages - 1)){
                break;
            }

            $p = $URL.'page='.$i.$query;
            if($page == $i){
                $active = 'active';
            }else{
                $active = '';
            }

            $link .= '<li class="'.$active.'">
                        <a href="'.$p.'">'.$i.'</a>
                    </li>';
        }

        if(($page + 2) < ($totalPages - 2)){
            $link .= '<li>
                    <a href="#">...</a>
                </li>';
        }
    }else{
        for($i = 3; $i <= ($totalPages - 2); $i++){
            $p = $URL.'page='.$i.$query;
            if($page == $i){
                $active = 'active';
            }else{
                $active = '';
            }

            $link .= '<li class="'.$active.'">
                        <a href="'.$p.'">'.$i.'</a>
                    </li>';
        }
    }

    if($totalPages > 2){
        if(($totalPages - 1) != 2){
            $p = $URL.'page='.($totalPages-1).$query;
            if($page == ($totalPages-1)){
                $active = 'active';
            }else{
                $active = '';
            }

            $link .= '<li class="'.$active.'">
                    <a href="'.$p.'">'.($totalPages-1).'</a>
                </li>';
        }

        $p = $URL.'page='.$totalPages.$query;
        if($page == $totalPages){
            $active = 'active';
        }else{
            $active = '';
        }

        $link .= '<li class="'.$active.'">
                    <a href="'.$p.'">'.$totalPages.'</a>
                </li>';
    }

    if($page == $totalPages){
        $link .= '<li class="next disabled">
            <a href="#">
                <i class="ace-icon fa fa-angle-double-right"></i>
            </a>
        </li>';
    }else{
        $next  = $URL.'page='.($page + 1).$query;
        $link .= '<li class="next">
                    <a href="'.$next.'">
                        <i class="ace-icon fa fa-angle-double-right"></i>
                    </a>
                </li>';
    }

    $link .= '</ul>';

    return $link;
}

// Get current microtime
function calculateTime() {
    list($usec, $sec) = explode(' ', microtime());
    return ((float) $usec + (float) $sec);
}


function pr($arr) {
	echo '<pre>';
    print_r($arr);
	echo '</pre>';
}


function pp() {
	pr($_POST);
}


/**
 *  JavaScript alert
 */
function jsAlert($msg) {
    echo "<script type='text/javascript'>alert(\"$msg\")</script>";
}


/**
 *  JavaScript redirect
 */
function jsRedirect($url, $die = true) {
    echo "<script type='text/javascript'>window.location.href=\"$url\"</script>";
    if($die){
    	die;
    }
}


// verify page
function verifyPage($page, $totalPages){
	if ($page > $totalPages || !is_numeric($page) || $page <= 0) {
		$page = 1;
	}
	
	return $page;
}


/**
 * Echo and die
 */
function eand($msg){
	echo $msg; die;
}


/**
 * Echo html br
 */
function br(){
	echo '<br />';
}


/**
 * Echo html hr
 */
function hr(){
	echo '<hr/>';
}


// echo hidden div with msg
function echoHiddenDiv($msg){
	$html = '<div style="display:none">'.$msg.'</div>';
	echo $html;
}


// Highlight keyword
function highlight($str, $find, $color){
	return str_replace($find, '<font color="'.$color.'">'.$find.'</font>', $str);
}

function daddslashes($string, $force = 1) {
	if(is_array($string)) {
		$keys = array_keys($string);
		foreach($keys as $key) {
			$val = $string[$key];
			unset($string[$key]);
			$string[addslashes($key)] = daddslashes($val, $force);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    $ckey_length = 4;
    $key = md5($key != '' ? $key : 'ASDFGsdfsdfsdfsdf');
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if($operation == 'DECODE') {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        }
        else{
            return '';
        }
    }
    else{
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}

function fsocketopen($hostname, $port = 80, &$errno, &$errstr, $timeout = 15) {
	$fp = '';
	if(function_exists('fsockopen')) {
		$fp = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
	} elseif(function_exists('pfsockopen')) {
		$fp = @pfsockopen($hostname, $port, $errno, $errstr, $timeout);
	} elseif(function_exists('stream_socket_client')) {
		$fp = @stream_socket_client($hostname.':'.$port, $errno, $errstr, $timeout);
	}
	return $fp;
}